import react from '@vitejs/plugin-react'
import svgr from 'vite-plugin-svgr'
import legacy from '@vitejs/plugin-legacy'
import { visualizer } from 'rollup-plugin-visualizer'
import { VITE_APP_VISUALIZER } from './index'
import { PluginOption } from 'vite'
import type { NormalizedOutputOptions, OutputBundle } from 'rollup'
import { URL } from 'url'

//@ts-ignore
import json_en from '../locales/en/lang.json'
//@ts-ignore
import json_CN from '../locales/zh-CN/lang.json'

const json = {
	'zh-CN': json_CN,
	en: json_en,
}

const LOCALE = 'zh-CN'

function isLegacyBundle(bundle: OutputBundle, options: NormalizedOutputOptions) {
	if (options.format === 'system') {
		const entryChunk = Object.values(bundle).find((output) => output.type === 'chunk' && output.isEntry)

		return !!entryChunk && entryChunk.fileName.includes('-legacy')
	}

	return false
}

export function createVitePlugin(command: 'build' | 'serve') {
	const isBuild = command === 'build'
	const vitePlugins: PluginOption[] = []
	if (isBuild) {
		vitePlugins.push(
			react({
				babel: {
					plugins: ['babel-plugin-styled-components'],
				},
			})
		)
	} else {
		vitePlugins.push(react())
	}
	vitePlugins.push(svgr())
	vitePlugins.push(
		legacy({
			targets: ['ie >= 10'],
			additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
			modernPolyfills: ['es.global-this'],
		})
	)
	//legacy sourcemap 始终去除
	vitePlugins.push({
		name: 'rm-legacy-sourcemap',
		apply: 'build',
		generateBundle(opts, bundle) {
			if (isLegacyBundle(bundle, opts)) {
				// avoid emitting duplicate assets
				for (const name in bundle) {
					if (/.+\.map$/.test(name)) {
						delete bundle[name]
					}
				}
			}
		},
	})
	if (isBuild && VITE_APP_VISUALIZER) {
		vitePlugins.push(
			visualizer({
				open: true,
				gzipSize: true,
				brotliSize: true,
			}) as PluginOption
		)
	}

	vitePlugins.push({
		name: 'set-build-time',
		apply: 'build',
		transform(code, id) {
			if (id.endsWith('/src/pages/logger/main.tsx')) {
				const buildTime = new Date().toLocaleString()
				code = code.replace(/window\.__BUILD_TIME__ =.*/, `window.__BUILD_TIME__ = "${buildTime}";`)
				return {
					code,
					map: null,
				}
			}
		},
	})

	vitePlugins.push({
		name: 'dev-reload',
		configureServer(server) {
			server.middlewares.use((req, res, next) => {
				// 自定义请求处理...
				if (/\/mcc\/manager\/([0-9a-zA-Z]+)/.test(req.url || '')) {
					let x = /\/mcc\/manager\/([0-9a-zA-Z]+)/.exec(req.url || '')
					if (x) {
						res.statusCode = 200
						res.end(`
								<!DOCTYPE html>
								<html>
									<head>
									<meta charset="utf-8">
									<script>
										window.location.href = '/manager.html?meetingMoid=${x[1]}'
									</script>
									</head>
									<body>
									</body>
								</html>`)
						return
					}
				}
				if (/\/meeting\/meetingSpace\/([0-9a-zA-Z]+)/.test(req.url || '')) {
					let x = /\/meeting\/meetingSpace\/([0-9a-zA-Z]+)/.exec(req.url || '')
					if (x) {
						res.statusCode = 200
						res.end(`
								<!DOCTYPE html>
								<html>
									<head>
									<meta charset="utf-8">
									<script>
										window.location.href = '/meetingSpace.html?meetingMoid=${x[1]}'
									</script>
									</head>
									<body>
									</body>
								</html>`)
						return
					}
				}
				if (/\/meeting\/index.html/.test(req.url || '')) {
					res.statusCode = 200
					res.end(`
								<!DOCTYPE html>
								<html>
									<head>
									<meta charset="utf-8">
									<script>
										window.location.href = '/index.html'
									</script>
									</head>
									<body>
									</body>
								</html>`)
					return
				}
				if (/\/portal\/login/.test(req.url || '')) {
					res.statusCode = 200
					res.end(`
                        <!DOCTYPE html>
                        <html>
                            <head>
                            <meta charset="utf-8">
                            <script>
                                window.location.href = '/meetingapiweb/login?username=sysmgr&password=888888'
                            </script>
                            </head>
                            <body>
                            </body>
                        </html>`)
					return
				}
				if (/\/web\/kdv\/biz\/i18n\/meeting\/lang.min.js/.test(req.url || '')) {
					let locale = LOCALE
					if (req.headers.referer) {
						const params = new URL(req.headers.referer)?.searchParams
						locale = params.get('en') === '' ? 'en' : LOCALE
					}
					res.statusCode = 200
					res.end(`
                        window.__i18n__ = {
                            locale: "zh_CN", // 当前语言
                            resources:{
                                "zh_CN":{
                                    "translation": ${JSON.stringify(json[locale])}
                                }
                            }
                        }
                        `)
					return
				}
				if (/\/web\/kdv\/biz\/i18n\/meeting\/loader.min.js/.test(req.url || '')) {
					let locale = LOCALE
					if (req.headers.referer) {
						const params = new URL(req.headers.referer)?.searchParams
						locale = params.get('en') === '' ? 'en' : LOCALE
					}
					req.url = `/locales/${locale}/lang.js`
				}
				if (/\/web\/kdv\/biz\/i18n\/meeting\/lang.min.css/.test(req.url || '')) {
					let locale = LOCALE
					if (req.headers.referer) {
						const params = new URL(req.headers.referer)?.searchParams
						locale = params.get('en') === '' ? 'en' : LOCALE
					}
					req.url = `/locales/${locale}/lang.scss`
				}
				next()
			})
		},
	})

	vitePlugins.push({
		name: 'pre-transform-html',
		transformIndexHtml: {
			order: 'post',
			handler(html, { filename, server }) {
				return [
					{
						tag: 'script',
						attrs: {
							src: '/web/kdv/biz/i18n/meeting/lang.min.js?t=9.0',
						},
					},
					{
						tag: 'script',
						attrs: {
							src: '/web/kdv/biz/i18n/meeting/loader.min.js?t=9.0',
						},
					},
					{
						tag: 'script',
						attrs: {
							src: filename.includes(`/share/index.html`)
								? '../brand/index/index.js'
								: './brand/index/index.js',
						},
					},
					{
						tag: 'script',
						attrs: {
							nomodule: true,
							src: './static/data-time-format-timezone.js',
						},
					},
					// {
					// 	tag: 'link',
					// 	attrs: {
					// 		rel: 'stylesheet',
					// 		href: './brand/index/index.css',
					// 	},
					// },
					{
						tag: 'link',
						attrs: {
							rel: 'stylesheet',
							href: '/web/kdv/biz/i18n/meeting/lang.min.css?t=9.0',
						},
						injectTo: 'body',
					},
				]
			},
		},
	})

	return vitePlugins
}
